<?php

namespace app\model\user;

use app\base\BaseModel;
use app\factory\wxPay\WxV3Pay;
use think\facade\Config;

/**
 * 模型-UserBeanLogModel
 * Class UserBeanLogModel
 * @package app\model
 */
class UserBeanLogModel extends BaseModel
{

    protected $name = 'user_bean_log';

    /**
     * 范围查询-status
     *
     * @param [type] $query
     * @param [type] $status
     * @return void
     */
    public function scopeUserId($query, $user_id)
    {
        if (!empty($user_id)) {
            $query->where('user_id', $user_id);
        }
    }

    /**
     *
     * @param $query
     * @param $keyword
     */
    public function scopeKeyword($query, $keyword)
    {
        if (!empty($keyword)) {
            $query->whereLike('b.nick_name', '%' . trim($keyword) . '%', 'OR');
            $query->whereLike('b.phone', '%' . trim($keyword) . '%');
        }
    }

    /**
     * 范围查询-status
     * @param [type] $query
     * @param [type] $status
     * @return void
     */
    public function scopeType($query, $type)
    {
        if (!empty($type)) {
            if (is_array($type)) {
                $query->whereIn('type', $type);
            } else {
                $query->where('type', $type);
            }

        }
    }

    /**
     * 分页查询
     * @param string $type recharge 赠送 add活得 sub 扣除余额 use使用 deposit提现
     * @param $user_id
     * @param $current_page
     * @param $list_rows
     * @return array
     */
    public function getPageData($type = '', $user_id = '', $current_page, $list_rows)
    {

        $dataList = $this
            ->userId($user_id)
            ->type($type)
            ->order('id DESC')
            ->paginate(['page' => $current_page, 'list_rows' => $list_rows], false);
        $current = $dataList->currentPage();
        $total = $dataList->total();
        $limit = $dataList->listRows();
        $items = $dataList->items();
        $ret = ['total' => $total, 'current' => $current, 'limit' => $limit, 'dataList' => $items];
        return $ret;
    }

    /**
     * 趣豆(本金)变化日志
     * @param $user_id
     * @param $bean  趣豆变化数量
     * @param $type  变动类型  recharge 充值（购买大礼包）  use支付  sub 扣除余额 add返佣  return本金退回 deposit提现
     * @param string $detail
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function changeEarningsBean($user_id, $bean, $type, $detail = "")
    {
        if ($bean <= 0) {
            return [
                'code' => 0,
                'msg' => '操作失败'
            ];
        }
        $bean = floatval($bean);
        $user_model = new UserModel();
        $user_data = $user_model->where(['id' => $user_id])->field('bean')->find();
        $new_bean = 0;
        $new_deposit = 0;
        $new_last_bean = $user_data['bean'];
        switch ($type) {
            case 'recharge':
                $new_bean = floatval($new_last_bean) + floatval($bean);
                if (empty($detail)) {
                    $detail = "赠送获得趣豆";
                }
                break;
            case 'add':
                $new_bean = floatval($new_last_bean) + floatval($bean);
                if (empty($detail)) {
                    $detail = "获得趣豆";
                }
                break;
            case 'return':
                $new_bean = floatval($new_last_bean) + floatval($bean);
                if (empty($detail)) {
                    $detail = "本金趣豆退回";
                }
                break;
            case 'sub':
                $new_bean = floatval($new_last_bean) - floatval($bean);
                if ($new_bean < 0) {
                    return [
                        'code' => 0,
                        'msg' => '趣豆数量不足'
                    ];
                }
                if (empty($detail)) {
                    $detail = "扣除趣豆";
                }
                break;
            case 'use':
                $new_bean = floatval($new_last_bean) - floatval($bean);
                if ($new_bean < 0) {
                    return [
                        'code' => 0,
                        'msg' => '趣豆数量不足'
                    ];
                }
                if (empty($detail)) {
                    $detail = "使用趣豆";
                }
                break;
            case 'deposit':
                if ($bean < 50) {
                    $return_data['code'] = 0;
                    $return_data['msg'] = "趣豆提现额度不得小于50";
                    return $return_data;
                }

                $new_bean = floatval($new_last_bean) - floatval($bean);
                if ($new_bean < 0) {
                    return [
                        'code' => 0,
                        'msg' => '可提现的趣豆额不足'
                    ];
                }

                $deposit_config = Config::get('system.bean');
                if ($bean <= 50) {
                    $new_deposit = $bean - ($deposit_config['_50'] * $bean);
                } else if ($bean > 50 && $bean <= 300) {
                    $new_deposit = $bean - ($deposit_config['_300'] * $bean);
                } else if ($bean > 300 && $bean <= 600) {
                    $new_deposit = $bean - ($deposit_config['_600'] * $bean);
                } else if ($bean > 600 && $bean <= 1000) {
                    $new_deposit = $bean - ($deposit_config['_1000'] * $bean);
                }
                if (empty($detail)) {
                    $detail = "提现趣豆";
                }
//                $deposit_sn = "depositbean" . date("YmdHis") . rand(100, 999) . rand(100, 999);
                break;
        }

        $in_data = [
            'user_id' => $user_id,
            'last_bean' => $new_last_bean,
            'bean' => $bean,
            'deposit' => $new_deposit,
            'detail' => "(本金)" . $detail,
            'type' => $type,
            'add_time' => time(),
            'add_date' => date("Y-m-d H:i:s"),
            'day' => date("Y-m-d"),
            'status' => 1,
            'earnings' => 1
        ];
        $ret = self::insert($in_data);
        if ($ret !== false) {
            $up_data = [
                'bean' => $new_bean
            ];
            $ret = $user_model->where(['id' => $user_id])->update($up_data);
            if ($ret !== false) {
                return [
                    'code' => 1,
                    'msg' => '操作成功'
                ];
            }
        }
        return [
            'code' => 0,
            'msg' => '操作失败'
        ];
    }

    /**
     * 趣豆(收益)变化日志
     * @param $user_id
     * @param $bean  趣豆变化数量
     * @param $type  变动类型  recharge 充值（购买大礼包）  use支付  sub 扣除余额 add返佣
     * @param string $detail
     * @param string $openid
     * @param int $mold
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function changeEarnings($user_id, $bean, $type, $detail = "", $mold = 1, $openid = "")
    {
        if ($bean <= 0) {
            return [
                'code' => 0,
                'msg' => '操作失败'
            ];
        }
        $bean = floatval($bean);
        $user_model = new UserModel();
        $user_data = $user_model->where(['id' => $user_id])->field('bean,earnings_bean')->find();
        $new_bean = 0;
        $new_deposit = 0;
        $deposit_sn = "";
        $new_last_bean = $user_data['earnings_bean'];
        $now_bean = $user_data['bean'];
        $sub_bean = 0;
        switch ($type) {
            case 'recharge':
                $new_bean = floatval($new_last_bean) + floatval($bean);
                if (empty($detail)) {
                    $detail = "赠送获得趣豆";
                }
                break;
            case 'add':
                $new_bean = floatval($new_last_bean) + floatval($bean);
                if (empty($detail)) {
                    $detail = "获得趣豆";
                }
                break;
            case 'sub':
                $new_bean = floatval($new_last_bean) - floatval($bean);
                if ($new_bean < 0) {
                    return [
                        'code' => 0,
                        'msg' => '趣豆数量不足'
                    ];
                }
                if (empty($detail)) {
                    $detail = "扣除趣豆";
                }
                break;
            case 'use':
                $new_bean = floatval($new_last_bean) - floatval($bean);
                if ($new_bean < 0) {
                    return [
                        'code' => 0,
                        'msg' => '趣豆数量不足'
                    ];
                }
                if (empty($detail)) {
                    $detail = "使用趣豆";
                }
                break;
            case 'deposit':
                $new_bean = (floatval($new_last_bean) + floatval($now_bean)) - floatval($bean);
                if ($new_bean < 0) {

                    return [
                        'code' => 0,
                        'msg' => '趣豆数量不足'
                    ];
                }
                if (floatval($new_last_bean) < floatval($bean)) {
                    $sub_bean = (floatval($bean) - floatval($new_last_bean));
                    $new_bean = 0;
                } else {
                    $new_bean = floatval($new_last_bean) - floatval($bean);
                }
                $deposit_config = Config::get('system.deposit.bean');
                $new_deposit = $bean;
                if ($bean <= 50) {
                    $new_deposit = $bean - ($deposit_config['_50'] * $bean);
                } else if ($bean > 50 && $bean <= 300) {
                    $new_deposit = $bean - ($deposit_config['_50'] * $bean);
                } else if ($bean > 300 && $bean <= 600) {
                    $new_deposit = $bean - ($deposit_config['_300'] * $bean);
                } else if ($bean > 600 && $bean <= 1000) {
                    $new_deposit = $bean - ($deposit_config['_600'] * $bean);
                } else if ($bean > 1000) {
                    $new_deposit = $bean - ($deposit_config['_1000'] * $bean);
                }

                if (empty($detail)) {
                    $detail = "提现趣豆";
                }
                $deposit_sn = "depositbean" . date("YmdHis") . rand(100, 999) . rand(100, 999);
                break;
        }
        $in_data = [
            'user_id' => $user_id,
            'last_bean' => $new_last_bean,
            'bean' => $bean,
            'deposit' => $new_deposit,
            'deposit_sn' => $deposit_sn,
            'detail' => "(收益)" . $detail,
            'type' => $type,
            'add_time' => time(),
            'add_date' => date("Y-m-d H:i:s"),
            'day' => date("Y-m-d"),
            'status' => 1,
            'mold' => $mold,
            'earnings' => 2,
            'wxopen_id' => $openid
        ];
        $ret = self::insert($in_data);
        if ($ret !== false) {
            $id = self::getLastInsID();
            $up_data = [
                'earnings_bean' => $new_bean
            ];
            $ret = $user_model->where(['id' => $user_id])->update($up_data);
            if ($ret !== false) {
                if ($type == 'deposit') {
                    if ($new_last_bean > 0) {
                        $in_data = [
                            'user_id' => $user_id,
                            'last_bean' => $new_last_bean,
                            'bean' => $new_last_bean,
                            'detail' => "(收益)用户趣豆提现",
                            'type' => 'sub',
                            'add_time' => time(),
                            'add_date' => date("Y-m-d H:i:s"),
                            'day' => date("Y-m-d"),
                            'status' => 1,
                            'mold' => 1,
                            'earnings' => 2
                        ];
                        self::insert($in_data);
                    }
                    if ($sub_bean > 0) {
                        $out_data = UserBeanLogModel::changeEarningsBean($user_id, floatval($sub_bean), "sub", "用户趣豆提现");
                        if (empty($out_data['code'])) {
                            return self::returnMsg($out_data);
                        }
                    }
                    $up_data = [
                        'check' => 2,
                        'check_time' => time()
                    ];
                    self::where('id', $id)->update($up_data);
                }
                return [
                    'code' => 1,
                    'data' => $id,
                    'msg' => '操作成功'
                ];
            }
        }
        return [
            'code' => 0,
            'msg' => '操作失败'
        ];
    }

    /**
     * 验证提现审核通过的订单资金到账情况
     * @param int $end_time
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function checkDepositAccount($end_time = 0)
    {
        $map = [
            'type' => 'deposit',
            'check' => 2,
            'status' => 1
        ];
        $list = self::where($map)->field('id,deposit_sn,deposit')->where('check_time', '>', $end_time)->select();
        if (empty($list)) {
            return true;
        }
        $wx_pay3_tool = new WxV3Pay();
        $index = 1;
        foreach ($list as $value) {
            $res = $wx_pay3_tool->queryUserDeposit($value['deposit_sn']);
            if ($res['code'] == 1) {
                $up_data = [
                    'status' => 2
                ];
                self::where('id', $value['id'])->update($up_data);
            }
            if ($index % 10 == 0) {
                sleep(1);
            }
            $index++;
        }
    }

    /**
     * 获取当天提现的金额
     * @param string $user_id
     * @return float|int
     */
    public static function getDayDeposit($user_id = '')
    {
        $map = [
            'user_id' => $user_id,
            'type' => "deposit",
            'day' => date("Y-m-d")
        ];
        $deposit = self::where($map)->sum('bean');
        if (empty($deposit)) {
            return 0;
        }
        return $deposit;
    }
}
